#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <chrono>
std::mutex mtx;
std::condition_variable cv;
std::queue<int> queue;
bool finished = false;

void producer()
{
    for (int i = 0; i < 10; ++i)
    {
        {
            std::lock_guard<std::mutex> lock(mtx);
            queue.push(i);
            std::cout << "Produced: " << i << std::endl;
        }
        // 锁释放再去通知
        cv.notify_one();
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
    // 由生产者发出结束指令 这是对共享变量的修改
    {
        std::lock_guard<std::mutex> lock(mtx);
        finished = true;
    }
    cv.notify_one();
}

void consumer()
{
    // 什么时候退出
    while (true)
    {
        std::unique_lock<std::mutex> lock(mtx);
        cv.wait(lock, []
                { return !queue.empty() || finished; });
        if (finished)
        {
            break;
        }
        int value = queue.front();
        queue.pop();
        std::cout << "Consumed: " << value << std::endl;
    }
}

int main()
{
    std::thread producer_thread(producer);
    std::thread consumer_thread(consumer);

    producer_thread.join();
    consumer_thread.join();

    return 0;
}
